package com.iss.card.view;

import java.util.Collection;
import java.util.HashMap;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;

import com.iss.card.CardController;
import com.iss.card.CardController.EventHandler;
import com.iss.card.CardController.EventInfo;
import com.iss.card.CardController.EventType;
import com.iss.card.R;
import com.iss.card.common.ApplicationManager;
import com.iss.card.view.account.AccountAboutFargment;
import com.iss.card.view.account.AccountChangePasswordView;
import com.iss.card.view.account.AccountFeedBackFragment;
import com.iss.card.view.account.AccountFirstUse;
import com.iss.card.view.account.AccountLogInFragment;
import com.iss.card.view.account.AccountLogInFragment.OnLoginButtonCLick;
import com.iss.card.view.account.AccountRegisterView;
import com.iss.card.view.account.AccountRetrievePasswordView;
import com.iss.card.view.account.shake.ShakeFragment;
import com.iss.card.view.mycard.CardBagModel;
import com.iss.card.view.store.StoreDetailFragment;
import com.iss.card.view.store.StoreModel;

public class ContainerActivity extends FragmentActivity implements EventHandler,
OnLoginButtonCLick{

	private static final String TAG = ContainerActivity.class.getSimpleName();
	private Fragment frgStoreDetail;
	private Fragment frgMyCardDetail;
	private Fragment frgShakeDetail;
	private Fragment frgShakeResutilDetail;
	private Fragment fragFeedBack;
	private Fragment fragAbout;
	private Fragment fragNearStore;
	// private Fragment fragCityList;
	private FragmentManager mFragmentManager;
	private static HashMap<String, Fragment> fragmentMap = new HashMap<String, Fragment>();
	private int intentKey;
	private StoreModel mStoreModel;
	private CardBagModel mCardBagModel;
	// private GeographicPositionModel mGeographicPositionModel;

	private GestureDetector mGestureDetector;
	private CardController mController;

	private AccountFirstUse firstUseFrag;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_container);

		mFragmentManager = this.getSupportFragmentManager();
		initContainerActivity();
	}

	private void initContainerActivity() {

		// This needs to be created before setContentView
		mController = CardController.getInstance(this);

		// Must register as the first activity because this activity can modify
		// the list of event handlers in it's handle method. This affects who
		// the rest of the handlers the controller dispatches to are.
		mController.registerEventHandler(R.layout.activity_container, this);

		intentKey = (Integer) getIntent().getExtras().get(
				ApplicationManager.INTENT_KEY);

		switch (intentKey) {
		case ApplicationManager.INTENT_FRAGMENT_STORE_DETAIL:

			final String storeId = getIntent().getStringExtra(
					ApplicationManager.KEY_PUT_EXTRA_SELECTED_STORE_ID);
			final int productId = getIntent().getIntExtra(
					ApplicationManager.KEY_PUT_EXTRA_DEFAULT_PRODUCT_ID, 0);
			loadStoreDetailFrag(storeId, productId);
			break;
		case ApplicationManager.INTENT_FRAGMENT_MY_CARD:

			/*mCardBagModel = (CardBagModel) getIntent().getExtras().get(
					ApplicationManager.KEY_PUT_EXTRA_BY_MY_CARD);
			loadCardBagFrag();*/
			break;
		case ApplicationManager.INTENT_FRAGMENT_SHAKE:

			loadShakeFrag();
			break;
		case ApplicationManager.INTENT_FRAGMENT_FEED_BACK:

			loadFeedBack();
			break;
		case ApplicationManager.INTENT_FRAGMENT_ABOUT_US:

			loadAboutUs();
			break;
		// case ApplicationManager.INTENT_FRAGMENT_CITYLIST:
		// loadCityInfo();
		// break;
		case ApplicationManager.INTENT_FRAMENT_LOG_IN:
			loadLogInFrag();
			break;
		case ApplicationManager.INTENT_FRAGMENT_FIRES_USE:
			loadLogFirstUse();
			break;
		case ApplicationManager.INTENT_FRAGMENT_CHANGE_PASSWORD:
			loadChangePassword();
			break;
		default:
			break;
		}
	}

	private void loadChangePassword() {
		// TODO Auto-generated method stub
		Fragment fragChangePassword = new AccountChangePasswordView();
		putFragment("fragChangePassword", fragChangePassword);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.add(R.id.container_frame, fragChangePassword);
		ft.commit();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.e(TAG, "onDestroy");
		// mController.sendEvent(EventType.ACCOUNT_DELETE_ALL_FRAGMENT);
		mController.deregisterEventHandler(R.layout.activity_container);
		CardController.removeInstance(this);
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		if (frgStoreDetail != null) {
			((StoreDetailFragment) frgStoreDetail).backEvent();
		}
		// frgMyCardDetail.backEvent();
		// frgShakeDetail.backEvent();
		// frgShakeResutilDetail.backEvent();
		// fragFeedBack.backEvent();
		// fragAbout.backEvent();
		mController.deregisterEventHandler(R.layout.activity_container);
		
		Log.e(TAG, "finish");
	}


	private void loadStoreDetailFrag(String storeId, int productId) {
		frgStoreDetail = new StoreDetailFragment(storeId, productId);
		putFragment("frgStoreDetail", frgStoreDetail);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.add(R.id.container_frame, frgStoreDetail);
		ft.commit();
	}
//	Use MycardDetailMycardFragment instead
	
	/*
	private void loadCardBagFrag() {
		frgMyCardDetail = new MyCardDetailFragment(mCardBagModel);
		putFragment("frgMyCardDetail", frgMyCardDetail);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.add(R.id.container_frame, frgMyCardDetail);
		ft.commit();
	}
*/
	private void loadShakeFrag() {
		frgShakeDetail = new ShakeFragment();
		putFragment("frgShakeDetail", frgShakeDetail);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.add(R.id.container_frame, frgShakeDetail);
		ft.commit();
	}

	private void loadShakeResultFrag() {
//		frgShakeResutilDetail = new ShakeResultFragment();
//		putFragment("frgShakeResutilDetail", frgShakeResutilDetail);
//		FragmentTransaction ft = mFragmentManager.beginTransaction();
//		ft.add(R.id.container_frame, frgShakeResutilDetail);
//		ft.commit();
	}

	private void loadFeedBack() {

		fragFeedBack = new AccountFeedBackFragment();
		putFragment("fragFeedBack", fragFeedBack);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.add(R.id.container_frame, fragFeedBack);
		ft.commit();
	}

	private void loadAboutUs() {

		fragAbout = new AccountAboutFargment();
		putFragment("fragAbout", fragAbout);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.add(R.id.container_frame, fragAbout);
		ft.commit();
	}

	// private void loadCityInfo(){
	// fragCityList = new CityListFragment();
	// putFragment("fragCityList", fragCityList);
	// FragmentTransaction ft = mFragmentManager.beginTransaction();
	// ft.add(R.id.container_frame, fragCityList);
	// ft.commit();
	// }
	private void loadLogInFrag() {
		AccountLogInFragment logInfrag = new AccountLogInFragment();
		Bundle bundle = new Bundle();
		
		bundle.putString(ApplicationManager.KEY_LOGIN_FRAG_FIRED_BY, 
				getIntent().getExtras().getString(ApplicationManager.KEY_LOGIN_FRAG_FIRED_BY));
		logInfrag.setArguments(bundle);
		putFragment("logInfrag", logInfrag);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.add(R.id.container_frame, logInfrag);
		ft.commit();

	}
	
	private void loadLogFirstUse() {
		firstUseFrag = new AccountFirstUse();
		putFragment("firstUseFrag", firstUseFrag);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.replace(R.id.container_frame, firstUseFrag);
		ft.commit();

	}
	private void loadRegisterFrag(){
		Fragment registerFrag = new AccountRegisterView();
		putFragment("registerFrag", registerFrag);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.add(R.id.container_frame, registerFrag);
		ft.addToBackStack("registerFrag");
		ft.commit();
	}
	private void loadRetrievePasswordFrag(){
		Fragment RetrievewordFrag = new AccountRetrievePasswordView();
		putFragment("RetrievewordFrag", RetrievewordFrag);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.add(R.id.container_frame, RetrievewordFrag);
		ft.addToBackStack("RetrievewordFrag");
		ft.commit();
	}

	public boolean onTouchEvent(MotionEvent event) {
		if (mGestureDetector != null) {
			mGestureDetector.onTouchEvent(event);
		}
		return super.onTouchEvent(event);
	}

	public void setGestureDetector(GestureDetector detector) {
		this.mGestureDetector = detector;
	}

	@Override
	public long getSupportedEventTypes() {
		return EventType.ACCOUNT_SHAKE_RESUTIL
				| EventType.ACCOUNT_SHAKE_GO_LOOK
				| EventType.ACCOUNT_RETURN_SHAKE
				| EventType.ACCOUNT_DELETE_ALL_FRAGMENT
				| EventType.ACTION_RETURN;
	}

	@Override
	public void handleEvent(EventInfo event) {

		if (event.eventType == EventType.ACCOUNT_SHAKE_RESUTIL) {

			loadShakeResultFrag();
		} else if (event.eventType == EventType.ACCOUNT_SHAKE_GO_LOOK) {
			// TODO random store.
			// StoreModel model = (StoreModel) event.values;
			// loadStoreDetailFrag(model);
		} else if (event.eventType == EventType.ACCOUNT_RETURN_SHAKE) {

//			loadShakeFrag();
		} else if (event.eventType == EventType.ACCOUNT_DELETE_ALL_FRAGMENT) {
			deleteAllFragment();
		}else if(event.eventType == EventType.ACTION_RETURN){
			mFragmentManager.popBackStack();
		}
	}

	@Override
	public void eventsChanged() {

	}

	/**
	 * �������е�fragment
	 */
	private void deleteAllFragment() {
		Collection<Fragment> fragments = fragmentMap.values();
		for (Fragment arg0 : fragments) {
			if (arg0 != null) {
				FragmentTransaction ft = mFragmentManager.beginTransaction();
				ft.remove(arg0);
				ft.commit();
			}
		}
		fragmentMap.clear();
	}

	/**
	 * ��������Fragment
	 * 
	 * @param key
	 * @param value
	 */
	private void putFragment(String key, Fragment value) {
		fragmentMap.put(key, value);
	}

	@Override
	public void onRegister() {
		// TODO Auto-generated method stub
		loadRegisterFrag();
		
	}

	@Override
	public void onForgetPassword() {
		// TODO Auto-generated method stub
		loadRetrievePasswordFrag();
	}
}
